#include <iostream>
#include <cstdlib>
#include <Network.hpp>

using namespace std;

using namespace Network;
using namespace System;



void serverExample()
{
	cout << "Creating socket..." << endl;
	TcpSocket sock;
	
	cout << "Binding port..." << endl;
	sock.bind(IpEndPoint(IpAddress::ipv4_any, 4242));
	
	cout << "Listenning port..." << endl;
	sock.listen(5);
	
	cout << "Waiting new client..." << endl;
	TcpSocket csock = sock.accept();
	
	cout << "A client join has joined the server" << endl;
	
	cout << "Closing connection..." << endl;
	csock.finish();
	sock.finish();
}



void clientExample()
{
	cout << "Creating socket..." << endl;
	TcpSocket sock;
	
	cout << "Binding port..." << endl;
	sock.connect(IpEndPoint(IpAddress::ipv4_localhost, 4242));
	
	cout << "You are connected !" << endl;
	
	cout << "Closing connection..." << endl;
	sock.finish();
}



void dnsExample()
{
	cout << "Hostname : " << Dns::getHostName() << endl;
	
	cout << "127.0.0.1 hostname : " << Dns::getHostName(IpAddress("127.0.0.1")) << endl;
	
	cout << "Google.com IP adresses : " << endl;
	vector<IpAddress> address = Dns::getHostAddresses("google.com");
	for(unsigned int i=0 ; i<address.size() ; i++)
		cout << '\t' << address[i].ip() << endl;
}



class ThreadExample : public Thread
{
	protected:
	
	Mutex _mutex;
	
	
	public:
	
	void run()
	{
		int s = rand()%10;
		for(int i=0 ; i<25 ; i++)
			printNumber(s);
	}
	
	void printNumber(int n)
	{
		_mutex.lock();
		cout << "<" << n << ">";
		_mutex.unlock();
	}
};



void threadExample()
{
	ThreadExample thread;
	thread.start();
	
	int s = rand()%10;
	for(int i=0 ; i<25 ; i++)
		thread.printNumber(s);
	
	
	thread.wait();
	cout << endl;
}



int main(/*int argc, char* argv[]*/)
{
	try
	{
		cout << "Initialisation..." << endl;
		load();
		
		
		TcpSocket sock;
		
		sock.bind(IpEndPoint(IpAddress::ipv4_localhost, 4242));
    	sock.listen(5);
    	
    	cout << "Waiting new client..." << endl;
    	
    	TcpSocket csock = sock.accept();
    	cout << "A client join has joined the server : " << csock.localEndPoint() << endl;
		csock.finish();
		
		sock.finish();
		
		
		/*
		UdpSocket sock;
		string str = "1234567890";
		sock.sendto(IpEndPoint(IpAddress::ipv4_localhost, 1234), (const void*)str.c_str(), str.size());
		cout << "You are connected from " << sock.localEndPoint().ip() << ":" << sock.localEndPoint().port() << endl;
		
		while(1)
			cout << sock.available() << endl;
		sock.finish();
		
		cout << "Ending..." << endl;
		*/
		
		
		unload();
	}
	catch(SocketException& e)
	{
		cout << "Critical error : " << e.what() << endl;
	}
}



